<?php

class Service_iTunes extends Service implements IService
{
    
    static $moduleName = 'iTunes Music Store Parser';
    static $author = 'KnKill';
    static $version = '1.00';
    static $site = 'itunes.apple.com';
    static $mask = '.*itunes.apple.com.*';
    static $metaFields = array(
        META_LABEL,
        META_GENRES,
        META_RELEASE_DATE,
    );
    
    private $content;
    
    public function __construct($url) {
        $this->content = getPage($url);
        phpQuery::newDocumentHTML($this->content);
    }

    
    /**
     * getReleaseArtists
     */
    public function getReleaseArtists() {
       return array(trim(pq('#title h2 a')->eq(0)->text()));
    }
    
    
    /**
     * getReleaseTtitle
     */
    public function getReleaseTitle() {
        return trim(pq('#title h1')->eq(0)->text());
    }
    
    
    /**
     * getGenres
     */
    public function getGenres() {
        $genres = array();
        foreach(pq('li.genre a') as $genre) {
            $genres[] = trim(pq($genre)->text());
        }
        return $genres;
    }
    
    
    /**
     * getLabel
     */
    public function getLabel() {
        $label = pq('.copyright')->eq(0)->text();
        preg_match('/℗ ([0-9]{4}) (.*)/ui', $label, $matches);
        return trim($matches[2]);
    }
    
    
    /**
     * getReleaseDate
     */
    public function getReleaseDate() {
        $crd = pq('.release-date');
        $rd = $crd->children()->remove();
        $date = $crd->text();
        return date('Y-m-d', strtotime(trim($date)));
    }
    
    
    /**
     * getTracklist
     */
    public function getTracklist() {
        $tracklist = array();
        foreach(pq('.tracklist-table')->eq(0)->find('tbody tr.music') as $elem) {
            $elem = pq($elem);
            $rows = $elem->eq(0)->find('td');
            $index = $rows->eq(0)->find('span.index span')->text();
            $artist = $rows->eq(2)->find('a span.text')->text();
            $title = $rows->eq(1)->find('span span.text')->text();
            if($elem->hasClass('video') == true) {
                $title = $title . ' (Video)';
            }
            $length = $rows->eq(3)->find('span span.text')->text();
            if(empty($length) || empty($index)) {
                continue;
            }
            $tracklist[(int)$index] = array(
                'artists' => array($artist),
                'title' => trim($title),
                'length' => trim($length)
            );
        }
        return $tracklist;
    }
    
    public function getReview() {
        $review = trim(pq('.product-review p')->text());
        return (empty($review) ? false : $review);
    }
    
}